package example.service.impl;

import example.common.FileUtils;
import example.common.Result;
import example.entity.Selection;
import example.entity.SelectionResponse;
import example.mapper.SelectionResponseMapper;
import example.service.ISelectionResponseService;
import example.vo.FileNameAndPathVO;
import example.vo.SelectionResponseVO;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Objects;

@Service
public class SelectionResponseServiceImpl implements ISelectionResponseService {

    @Value("${file.selection_res_dir}")
    private String selectionResponseDir;

    @Resource
    private SelectionResponseMapper selectionResponseMapper;

    @Override
    public Result getSelectionResponse(Long selectionId) {
        List<SelectionResponseVO> selectionResponseVOList = selectionResponseMapper.getSelectionResponse(selectionId);
        return Result.ok(selectionResponseVOList);
    }

    @Override
    public Result getSelectionResponseFileName(Long id) {
        FileNameAndPathVO fileNameAndPathVO = selectionResponseMapper.getSelectionResponseFile(id);
        return Result.ok(fileNameAndPathVO.getFileName());
    }

    @Override
    public void getSelectionResponseFile(Long id, HttpServletResponse response) {
        FileNameAndPathVO fileNameAndPathVO = selectionResponseMapper.getSelectionResponseFile(id);
        String fileName = fileNameAndPathVO.getFileName();
        String filePath = fileNameAndPathVO.getFilePath();
        FileUtils.download(fileName, filePath, response);
    }

    @Override
    public Result uploadZip(MultipartFile file, Long selectionId, String departmentName) {
        String fileName = StringUtils.cleanPath(Objects.requireNonNull(file.getOriginalFilename()));
        String filePath = selectionResponseDir + "\\" + fileName;
        File newFile = new File(filePath);
        newFile.getParentFile().mkdirs();
        try {
            file.transferTo(newFile);
        } catch (IOException e) {
            return Result.fail("上传失败！");
        }
        SelectionResponse selectionResponse = new SelectionResponse();
        selectionResponse.setSelectionId(selectionId);
        selectionResponse.setDepartmentName(departmentName);
        selectionResponse.setFileName(fileName);
        selectionResponse.setFilePath(filePath);
        selectionResponseMapper.uploadZip(selectionResponse);
        return Result.ok("文件上传成功！");
    }
}
